package com.acme.bankapp.domain.bank;


import com.acme.bankapp.domain.bank.client.Client;
import com.acme.bankapp.service.bank.collection.ClientsCollection;
import com.acme.bankapp.service.bank.listener.ClientRegistrationListener;

import java.util.Date;

/**
 * This class represents bank
 *
 * @author Alexander Kotov
 */

public class Bank {

    private static final int INIT_CLINET_COUNT = 8;
    private ClientsCollection clientsCollection;
    private ClientRegistrationListener[] listeners;

    public Bank() {

        clientsCollection = new ClientsCollection(INIT_CLINET_COUNT);
        addClientRegistrationListener(new ClientRegistrationListener() {
            /**
             * {@inheritDoc}
             */
            @Override
            public void onClientAdded(Client client) {
                System.out.format("Time: %s, client: %s%n", new Date(), client);
            }
        });
    }

    public Bank(ClientRegistrationListener... listeners) {
        this.listeners = listeners;
    }

    /**
     * This method add client registration listener
     *
     * @param listener listener to add
     */
    public void addClientRegistrationListener(ClientRegistrationListener listener) {
        if (listeners == null) {
            final int initialListenersCount = 1;
            listeners = new ClientRegistrationListener[initialListenersCount];
            listeners[0] = listener;
        } else {
            ClientRegistrationListener[] newListeners = new ClientRegistrationListener[listeners.length + 1];
            System.arraycopy(listeners, 0, newListeners, 0, listeners.length);
            newListeners[listeners.length] = listener;
            listeners = newListeners;
        }
    }

    /**
     * @return list of bank clients
     */
    public Client[] getClients() {
        return clientsCollection.getClients();
    }

    /**
     * This method for add client object to bank object
     *
     * @param client represents {@link Client} object
     */
    public void addClient(Client client) {
        clientsCollection.insertClient(client);
        for (ClientRegistrationListener listener : listeners) {
            listener.onClientAdded(client);
        }
    }
}
